package com.weavernorth.promotionPlan.service;

import com.alibaba.fastjson.JSONObject;
import com.weaver.general.Util;
import com.weavernorth.util.Logger4jUtil;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.security.core.MD5;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;

import static com.weavernorth.util.MD5Util.md5Encryption;

/**
 * @Author: BruseeWang
 * @Date: 2020/11/12 16:37
 * @Description: 促销方案审批状态返回接口
 */
public class returnMessageService implements Action {
    private Logger log = Logger4jUtil.getLoggerByName("/action/returnMessageService/");
    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean bb = new BaseBean();
        int objid=requestInfo.getObjid();
        log.info("objId:"+objid);
        String requestid = requestInfo.getRequestid();//请求ID
        log.info("请求id:"+requestid);
        String workflowid = requestInfo.getWorkflowid();//流程ID
        log.info("工作流id:"+workflowid);
        String src = requestInfo.getRequestManager().getSrc();//当前操作类型submit:提交/reject:退回
        log.info("流程操作："+src);
        String remark = requestInfo.getRequestManager().getRemark();//当前用户提交时的签字意见
        remark=delHtmlTag(remark);
        log.info("测试审批意见："+remark);

        String tablename = requestInfo.getRequestManager().getBillTableName();//表单名称
        //logtype签字类型：0：批准 <br>1：保存 <br>2：提交 <br>3：退回 <br>4：重新打开 <br>5：删除 <br>6：激活 <br>7：转发
        //9：批注 <br>a：意见征询 <br>b：意见征询回复 <br>e：强制归档 <br>h：转办 <br>i：干预 <br>j：转办反馈
        //s：督办 <br>t：抄送
        //获取审批节点
        String sql = " select a.cxfabh,a.djbh,l.logtype status,wr.workflowid,l.nodeid,l.remark,l.logtype from " + tablename + " a," +
                "workflow_requestbase wr,workflow_requestlog l where a.requestid = wr.requestid "+
                "AND a.requestid=l.requestid AND a.requestid = wr.requestid  and l.logtype in('2','3') and a.requestid =" + requestid+"" +
                " ORDER BY l.operatedate DESC,l.operatetime DESC";
        log.info("查询条件："+sql);
        RecordSet rs=new RecordSet();
        String strCxfabh="";
        String strDjCode="";//单据编号
        String strStatus="0";//未提交
        if("reject".equals(src)){
            strStatus="2";//不同意
        }else{
            strStatus="1";//同意
        }
        rs.execute(sql);
        int index=0;
        while (rs.next()){
            if(index==0) {
                strCxfabh = Util.null2String(rs.getString("cxfabh"));//促销方案编号
                strDjCode = Util.null2String(rs.getString("djbh"));//单据编号
                //strStatus = Util.null2String(rs.getString("status"));//流程审批状态
            }
            index++;
        }
        log.info("促销方案编号:"+strCxfabh);
        log.info("单据编号:"+strDjCode);
        log.info("流程审批状态:"+strStatus);
        JSONObject  jsonResult = new JSONObject();
        jsonResult.put("status",strStatus);
        jsonResult.put("cxfabh", strCxfabh);
        jsonResult.put("remark", delHtmlTag(remark));
        jsonResult.put("djbh", strDjCode);

        String param = jsonResult.toJSONString();
        //"http://10.2.0.23:18084/FY_TP_SERVICE/FY_BPM_SERVICE.json?method=salesPromotion&appId=erdosbpm&sign=E64A1CB80553FEA277A0FD0CF47DD3B7";
        String strUrl = Util.null2String(bb.getPropValue("cxfaFromV8", "url"));
//        MD5 md5=new MD5();
        String strS="erdosbpm"+jsonResult.toJSONString();
        log.info("md5要加密的字符串："+strS);
        String strSign= null;
        try {
            strSign = md5Encryption(strS);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("md5加密异常："+e.toString());
        }
        log.info("md5加密后的字符串："+strSign.toUpperCase());
        strUrl=strUrl+strSign.toUpperCase();
        log.info("接口请求地址："+strUrl);
        String strResponse= null;
        try {
            strResponse = senDealPost(strUrl,jsonResult,log);
            JSONObject jsonObject = JSONObject.parseObject(strResponse);
            String requestNo=jsonObject.getString("requestNo");
            log.info("requestNo："+requestNo);
            String result=jsonObject.getString("success");
            log.info("result："+result);
            String message=jsonObject.getString("errorMessage");
            log.info("message："+message);
            if(result.equals("false")){
                //当前促销方案非提交状态，无法审核:代表v8系统该单据已经审核完成
                requestInfo.getRequestManager().setMessagecontent(message);
                return Action.FAILURE_AND_CONTINUE;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.info("接口异常："+e.toString());
            requestInfo.getRequestManager().setMessagecontent(e.toString());
            return Action.FAILURE_AND_CONTINUE;
        }
        log.info("V8响应结果："+strResponse);
        return SUCCESS;
    }

    public static String delHtmlTag(String str){
        String newstr = "";
        newstr = str.replaceAll("<[.[^>]]*>","");
        newstr = newstr.replaceAll(" ", "");
        newstr = newstr.replaceAll("\r|\n", "");
        return newstr;
    }

    /**
     * 发送post请求,json格式
     * @param strUrl       请求路径
     * @param jsonParam     请求体
     * @return
     * @throws IOException
     */
    public static String senDealPost(String strUrl, JSONObject jsonParam,Logger log) throws IOException {
        String strBody = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(strUrl);
        //装填参数
        StringEntity stringEntity = new StringEntity(jsonParam.toString(), "utf-8");
        stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(stringEntity);
        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        try {
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
//          log.info("返回状态=="+response);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }

        return strBody;
    }
    }
